/*
 * Copyright (C) 2010-2015 znyd Inc.All Rights Reserved.
 */
package edu.ycu.aladdin.web.dao.impl;

import edu.ycu.aladdin.web.dao.OauthDao;
import edu.ycu.aladdin.web.dto.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="mailto:wangruihuan@abitai.com">王瑞环</a>
 * @since 2019-01-16 11:33 AM
 */
@Repository
public class OauthDaoImpl implements OauthDao {

    @Autowired
    RedisTemplate redisTemplate;


    @Value("${aladdin.session.timeout}")
    private int sessionTimeout;


    @Override
    public User login(User user) {

        if (user != null) {

            String uid = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(uid
                    , user.getId(), sessionTimeout, TimeUnit.MINUTES);
            user.setUid(uid);
        }
        return user;
    }

    @Override
    public void logout(String sso) {
        redisTemplate.delete(sso);
    }

    @Override
    public boolean hasLogged(String sso) {
        return getUserId(sso) == null;
    }

    @Override
    public String getUserId(String sso) {
        return (String) redisTemplate.opsForValue().get(sso);
    }
}
